package com.supplychainapi.controller;

/**
 * Created by wangziqi on 2017/9/26.
 */

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.joindata.inf.common.basic.exceptions.ServiceException;
import com.supplychainapi.common.ApiVersion;
import com.supplychainapi.common.RestResponse;
import com.supplychainapi.common.enums.ExceptionMessage;
import com.supplychainapi.domain.LoginCache;
import com.supplychainapi.model.ScmTbtreetype;
import com.supplychainapi.param.ScmTbtreebuildParam;
import com.supplychainapi.proxy.ValidateHelper;
import com.supplychainapi.service.IScmTbtreebuildService;
import com.supplychainapi.service.IScmTbtreebuildTypeService;
import com.supplychainapi.utils.Constants;
import com.supplychainapi.utils.PathUitls;
import io.swagger.annotations.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;

/**
 * 分类树
 *
 * @Time 2017年10月10
 * @author wangziqi
 */
@RequestMapping(PathUitls.ROOT_PHONE+"/{version}/treebuild")
@RestController
@Api(value = "TreeBuildController", description = "分类树")
public class TreeBuildController extends BaseController {

    private Logger logger = LogManager.getLogger(this.getClass());
    @Autowired
    IScmTbtreebuildService tbtreebuildService;

    @Autowired
    IScmTbtreebuildTypeService typeService;

    @ApiVersion(1)
    @ApiOperation(value="新建分类", notes="")
    @RequestMapping(value = "/addClass", method= RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "fsTreeTypeId", value = "分类类型;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fsNodeText", value = "分类名称;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fdNodeLevel", value = "分类级别从1开始;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fdParentNodeCode", value = "父节点代码;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fsNodeFullText", value = "分类全称,一级_二级_三级;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType = "query", name = "fsNodeCode", value = "分类编码;swagger", required = true, dataType = "string", defaultValue = "")

    })
    public RestResponse addClass(@ApiIgnore LoginCache loginCache,@ApiIgnore @RequestBody ScmTbtreebuildParam model) throws ServiceException {
        model.setFsShopGUID(loginCache.getFsShopGUID());
        model.setFsCreateUserId(loginCache.getFsUserId());
        model.setFsCreateTime(new Date());
        model.setFsCreateUserName(loginCache.getFsUserName());
        return RestResponse.success(tbtreebuildService.saveTreeBuild(model));
    }

    @ApiVersion(1)
    @ApiOperation(value="修改分类", notes="")
    @RequestMapping(value = "/updateClass", method= RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "fsTreeTypeId", value = "分类类型;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fsNodeText", value = "分类名称;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fdNodeLevel", value = "分类级别从1开始;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fdParentNodeCode", value = "父节点代码;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fsNodeFullText", value = "分类全称,一级_二级_三级;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fiSort", value = "排序从1开始;swagger", required = false, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fiStatus", value = "0正常9禁用;swagger", required = false, dataType = "string", defaultValue = "0"),
            @ApiImplicitParam(paramType="query", name = "fsNodeCode", value = "节点代码主键;swagger", required = true, dataType = "string", defaultValue = ""),

    })
    public RestResponse updateClass(@ApiIgnore LoginCache loginCache,@ApiIgnore @RequestBody ScmTbtreebuildParam model) throws ServiceException {
        model.setFsShopGUID(loginCache.getFsShopGUID());
        model.setFsUpdateUserId(loginCache.getFsUserId());
        model.setFsUpdateTime(new Date());
        model.setFsUpdateUserName(loginCache.getFsUserName());
        return RestResponse.success(tbtreebuildService.updateTreeBuild(model));
    }

    @ApiVersion(1)
    @ApiOperation(value="删除分类", notes="")
    @RequestMapping(value = "/deleteClass", method= RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "fsTreeTypeId", value = "分类类型;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fsNodeCode", value = "分类代码;swagger", required = true, dataType = "string", defaultValue = ""),
    })
    public RestResponse deleteClass(@ApiIgnore LoginCache loginCache,@ApiIgnore @RequestBody ScmTbtreebuildParam model) throws ServiceException {
        model.setFsShopGUID(loginCache.getFsShopGUID());
        return RestResponse.success(tbtreebuildService.deleteTreeBuild(model));
    }


    @ApiVersion(1)
    @ApiOperation(value="修改分类type", notes="")
    @RequestMapping(value = "/updateClassType", method= RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "fsTreeTypeId", value = "分类类型;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fiClassLvl", value = "最大级数;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fsTreeTypeName", value = "名称;swagger", required = true, dataType = "string", defaultValue = ""),
    })
    public RestResponse updateClassType(@ApiIgnore LoginCache loginCache,@ApiIgnore @RequestBody ScmTbtreetype model) throws ServiceException {
        ValidateHelper.validate(model);
        model.setFsUpdateTime(new Date());
        model.setFsShopGUID(loginCache.getFsShopGUID());
        model.setFsUpdateUserId(loginCache.getFsUserId());
        model.setFsUpdateUserName(loginCache.getFsUserName());
        ScmTbtreebuildParam  param=new ScmTbtreebuildParam();
        param.setFiStatus((short) 1);
        param.setFsShopGUID(loginCache.getFsShopGUID());
        param.setFsTreeTypeId(model.getFsTreeTypeId());
        param.setFiDataKind((short) 1);
        param.setFsNodeText("未分类");
        param.setFdNodeLevel((short) 1);
        param.setFsNodeFullText("未分类");
        param.setFsNodeFullCode("1");
        param.setFsNodeCode("1");
        param.setFdParentNodeCode("0");
        param.setFsCreateUserName(loginCache.getFsUserName());
        param.setFsCreateTime(new Date());
        param.setFsCreateUserId(loginCache.getFsUserId());
        switch (model.getFsTreeTypeId()) {
            case Constants.SUPPLIER_CLASS:
                if (model.getFiClassLvl() > Constants.SUPPLIER_CLASS_LEVEL) {
                    throw ExceptionMessage.tree_type_lv_error.getServiceException();
                }
                break;
            case Constants.MATERIAL_CLASS:
                if (model.getFiClassLvl() > Constants.MATERIAL_CLASS_LEVEL) {
                    throw ExceptionMessage.tree_type_lv_error.getServiceException();
                }
                break;
            case Constants.CUST_CLASS:
                if (model.getFiClassLvl() > Constants.CUST_CLASS_LEVEL) {
                    throw ExceptionMessage.tree_type_lv_error.getServiceException();
                }
                break;
            default:
                break;
        }
        for (int i = 1; i <= model.getFiClassLvl(); i++) {
            param.setFsNodeCode(i+"");
            tbtreebuildService.deleteTreeBuild(param);
            if (i == 1) {
                tbtreebuildService.saveTreeBuild(param);
            }
            if (i == 2) {
                ScmTbtreebuildParam two = new ScmTbtreebuildParam();
                BeanUtils.copyProperties(param, two);
                two.setFsNodeFullText("未分类_未分类.");
                two.setFdNodeLevel((short) 2);
                param.setFsNodeText("未分类.");
                param.setFdNodeLevel((short) 2);
                param.setFsNodeCode("2");
                param.setFdParentNodeCode("1");
                param.setFsNodeFullCode("1|2");
                tbtreebuildService.saveTreeBuild(param);
            }
            if (i == 3) {
                ScmTbtreebuildParam two = new ScmTbtreebuildParam();
                BeanUtils.copyProperties(param, two);
                two.setFsNodeFullText("未分类_未分类._未分类..");
                two.setFdNodeLevel((short) 3);
                param.setFsNodeText("未分类..");
                param.setFdNodeLevel((short) 3);
                param.setFsNodeCode("3");
                param.setFsNodeFullCode("1|2|3");
                param.setFdParentNodeCode("2");
                tbtreebuildService.saveTreeBuild(param);
            }
        }
        return RestResponse.success(typeService.update(model));
    }


    @ApiVersion(1)
    @ApiOperation(value="排序", notes="")
    @RequestMapping(value = "/classSorting", method= RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "fsTreeTypeId", value = "分类类型;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fsNodeCode", value = "分类代码;swagger", required = true, dataType = "string", defaultValue = ""),
            @ApiImplicitParam(paramType="query", name = "fiSort", value = "排序从1开始;swagger", required = true, dataType = "string", defaultValue = ""),

    })
    public RestResponse classSorting(@ApiIgnore LoginCache loginCache,@ApiParam("ScmTbtreebuildParam model list") @RequestBody JSONObject json) throws ServiceException {
        List array=json.getJSONArray("list");
        List<ScmTbtreebuildParam> tbtreebuildParams=Lists.newArrayList();
        array.stream().forEach(e->{
            ScmTbtreebuildParam param=JSONObject.parseObject(e.toString(),ScmTbtreebuildParam.class);
            tbtreebuildParams.add(param);
        });
        for (ScmTbtreebuildParam param : tbtreebuildParams) {
            param.setFsShopGUID(loginCache.getFsShopGUID());
            tbtreebuildService.classSorting(param);
        }
        return RestResponse.success();
    }
    
    
	@ApiVersion(1)
	@ApiOperation("获取分类等级")
	@RequestMapping(value = "/getScmTbtreebuildFdNodeLevelInfo", method=RequestMethod.GET)
	public RestResponse<Integer>  getScmTbtreebuildFdNodeLevelInfo(@ApiIgnore LoginCache loginCache,@ApiParam(value = "分类类型", required = true)@RequestParam String fsTreeTypeId){
		logger.info("fsTreeTypeId={}",fsTreeTypeId);
		 switch (fsTreeTypeId) {
         case Constants.SUPPLIER_CLASS:
        	 return RestResponse.success(Constants.SUPPLIER_CLASS_LEVEL);
         case Constants.MATERIAL_CLASS:
        	 return RestResponse.success(Constants.MATERIAL_CLASS_LEVEL);
         case Constants.CUST_CLASS:
        	 return RestResponse.success(Constants.CUST_CLASS_LEVEL);
         default:
             break;
         }
		return RestResponse.success();
	}
}
